<?php
namespace app\beautiful\controller\miniapp\member\goods;
use app\BaseController;
use app\beautiful\controller\admin\setting\Send;
use app\beautiful\logic\PartnerLogic;
use app\beautiful\logic\printer\PrinterLogic;
use app\beautiful\model\order\OrderGoodsGroupDetailModel;
use app\beautiful\model\order\OrderGoodsModel;
use app\beautiful\model\setting\SendCityModel;
use app\beautiful\model\setting\SendKuaidiModel;
use app\beautiful\model\setting\SendSelfModel;
use app\common\logic\SmsLogic;
use app\beautiful\logic\order\OrderLogic;
use app\beautiful\model\mall\FreightTemplateModel;
use app\beautiful\model\mall\FreightTemplatePieceModel;
use app\beautiful\model\setting\SettingBalanceModel;
use app\beautiful\model\setting\SettingIntegralModel;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\order\GoodsOrderModel;
use app\beautiful\model\setting\SettingSmsModel;
use app\common\model\ShopModel;
use think\facade\Db;
use app\beautiful\logic\LogsLogic;
use app\beautiful\logic\MemberWalletLogic;
class Order extends BaseController{
 
    
    //获取用户的订单信息
    public function getGoodsOrderList(){
        $status = $this->request->param('status/d');
        $where= [
            ['shop_id','=', $this->request->shopId],
            ['member_id','=', $this->request->memberId],
            ['is_delete','=',0]
        ];
        switch ($status){ //查询订单的状态
            case 0: // 待付款
                $where[] = ['status','=',1];
                break;
            case 1: //待发货
                $where[] = ['status','=',2];
                break;
            case 2: //待收货
                $where[] = ['status','=',3];
                break;
            case 3://待自提
                $where[] = ['status','=',4];
                break;
            case 4://已完成  取消的订单也在已完成里面
                 $where[] = ['status','IN',[8,-1]];
                break;
            case 9://待分配
                $where[] = ['status','=',9];
                break;
        }
        $datas = GoodsOrderModel::with(['skus'])->where($where)
            ->json(['order_send_time'],true)
            ->field('order_id,order_type,logistics_type,total_price,is_paid,status,add_time,order_send_time,receiving_name,receiving_mobile,receiving_address_province,receiving_address_city,receiving_address_county,receiving_address_info')
            ->json(['order_send_time'],true)
            ->limit($this->request->limit)
            ->page($this->request->page)
            ->order(['order_id'=>'desc'])
            ->select()->append(['order_time','djs_time'])
            ->toArray();
        return $this->success([
            'list' => $datas
        ]);
    }
    
    
    //使用余额支付订单
    public function getGoodsOrderMoneyPay(){
        $order_id = $this->request->param('order_id/d');
        if(empty($order_id)){
            return $this->error('请选择要支付的订单');
        }
        if( null === $order = GoodsOrderModel::find($order_id)){
            return $this->error('订单不存在');
        }
        if($order->status != 1 || $order->is_delete == 1){
            return $this->error('订单不在未支付状态');
        }
        $time = time() - 900;//订单15分钟
        if($order->add_time < $time){ //如果 订单超过15分钟则不能支付了
            return $this->error('订单支付已经超时了，不能继续支付');
        }
        if($order->shop_id != $this->request->shopId || $order->member_id != $this->request->memberId){
            return $this->error('订单不存在'); 
        }
        Db::startTrans();
        try{
            if(!empty($order->member_coupon_id)){
                if(null === $myCoupon = MemberCouponModel::find($order->member_coupon_id)){
                    Db::rollback();
                    return $this->error('优惠券不存在');
                }
                if($myCoupon->status == 1){
                    Db::rollback();
                    return $this->error('优惠券不存在');
                }
                $myCoupon->status = 1;
                $myCoupon->save();
                LogsLogic::coupon($this->request->shopId, $this->request->memberId, -1, 12, $order->member_coupon_id, '', 0);
            }
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $this->request->memberId);
            if(!empty($order->use_integral)){ //使用积分
                $res = $MemberWalletLogic->useIntegral($order->use_integral, 9);
                if($res == false){
                    Db::rollback();
                    return $this->error($MemberWalletLogic->getError());
                }
            }
            $needPay = round(($order->total_price * 100 + $order->freight * 100 - $order->coupon_money * 100 - $order->integral_balance * 100)/100,2);
            if($needPay <= 0){
                Db::rollback();
                $this->error('支付金额不正确');
            }
            $res = $MemberWalletLogic->useBalance($needPay, $order->total_price + $order->freight , 8); //商城购物使用
            if($res == false){
                Db::rollback();
                return $this->error($MemberWalletLogic->getError());
            }
            $order->is_paid = 1;
            $order->pay_time = time();

            $order->status = $order->logistics_type == 1? 2 : 4; //订单的状态值

            if($order->logistics_type == 3) $order->status = 9;

            if($order->order_type == 'set_meal') $order->status = 10;
            
            $order->pay_type = 'money';
            $order->verify_code = getVerifyCode($order_id);
            $order->save();

            //修改套餐有效期
            if($order->order_type == 'set_meal'){
                $order_goods = OrderGoodsModel::where(['order_id'=>$order_id,'is_delete'=>0])->find();
                if($order_goods && $order_goods->use_type!=1){
                    $end_time = goodsEndTime($order_goods,$order);
                    $order_goods->start = $end_time->start_time;
                    $order_goods->end = $end_time->end_time;
                    $order_goods->save();
                }


            }

            //发送短信给管理员
            try{
                $sms_setting = SettingSmsModel::where([['shop_id','=',$this->request->shopId]])->find();
                if(null !== $sms_setting){
                    if($sms_setting->order_notice_admin==1){
                        $sms_logic= new SmsLogic();
                        $params=[
                            'money'=>$needPay,
                        ];
                        $sms_logic->send($this->request->shopId,$sms_setting->boss_mobiles,$params,'orderNoticeAdmin');
                    }
                }
            }catch (\Exception $e){

            }
            //单店版下单支付就分红，多店版收货后订单完成才分红
            if($order->from_type == 1){
                //分红
                $PartnerLogic = new PartnerLogic($order->shop_id);

                $PartnerLogic->commissionNew($order->member_id,$needPay,'order',$order_id);
            }

            //打印机
            if($order->logistics_type == 2){
                $type = 'self';
            }
            if($order->logistics_type == 3){
                $type = 'city';
            }
            if(in_array($order->logistics_type,[2,3])){

                $printer_logic = new PrinterLogic($this->request->shopId);
                $printer_logic->print($type,$order_id);
            }


            Db::commit();
            return $this->success('余额支付成功');
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
    
    
    
    
   
    //获取运费模版
    public function getFreightTemplate(){
         if(null === $freight_template = FreightTemplateModel::where('shop_id',$this->request->shopId)->find()){
             return $this->success(['freight_template'=>null]);
         }
         $piece = [];
         if($freight_template->freight_type==2){
            if(null === $freight_template_piece = FreightTemplatePieceModel::where('freight_template_id',$freight_template->freight_template_id)->find()){
                return  $this->success(['freight_template'=>null]);
            }
            $piece = [
                'base_piece_num'=>isset($freight_template_piece) ? $freight_template_piece->base_piece_num : '',
                'base_piece_price'=>isset($freight_template_piece) ? $freight_template_piece->base_piece_price : '',
                'add_piece_num'=>isset($freight_template_piece) ? $freight_template_piece->add_piece_num : '',
                'add_piece_price'=>isset($freight_template_piece) ? $freight_template_piece->add_piece_price : '',
                'piece_data'=>isset($freight_template_piece) ? $freight_template_piece->piece_data : [],
            ];
         }
        $detail=[
            'name'=>$freight_template->name,
            'hours'=>$freight_template->hours,
            'freight_type'=>$freight_template->freight_type,
            'valuation_type'=>$freight_template->valuation_type,
            'no_delivery_area'=>$freight_template->no_delivery_area,
            'piece' => $piece,
        ];
        return $this->success([
            'freight_template' => $detail
        ]);
    }
       
    public  function getGoodsOrderDetail(){
        $order_id=$this->request->param('order_id/d',0);
        if(empty($order_id)) return $this->error('订单不存在');
        $where= [
            ['shop_id','=', $this->request->shopId],
            ['member_id','=', $this->request->memberId],
            ['is_delete','=',0],
            ['order_id','=',$order_id]
        ];
        $datas = GoodsOrderModel::with(['skus'])->json(['order_send_time'],true)->where($where)->find();
        if(null === $datas) return $this->error ('订单不存在');
        $datas->append(['order_time','djs_time','youhui','pay_time_format','pay_type_mean'])
            ->toArray(); 
        return $this->success([
            'detail' => $datas
        ]);
    }
    
    //确定收货
    public function yesOrder(){
        $order_id=$this->request->param('order_id/d',0);
        if(empty($order_id)) return $this->error('订单不存在');
        $order=GoodsOrderModel::find($order_id);
        if(null === $order) return $this->error ('订单不存在');
        if($order->shop_id != $this->request->shopId || $order->member_id != $this->request->memberId){
            return $this->error('订单不存在');
        }
        if($order->status != 3) return $this->error ('订单状态不正确');
        $order->status = 8;
        $order->save();
        return $this->success('确定成功');
    }
    public function deleteOrder(){ //只能删除 已完成的订单
        $order_id=$this->request->param('order_id/d',0);
        if(empty($order_id)) return $this->error('订单不存在');
        $order=GoodsOrderModel::find($order_id);
        if(null === $order) return $this->error ('订单不存在');
        if($order->shop_id != $this->request->shopId || $order->member_id != $this->request->memberId){
            return $this->error('订单不存在');
        }
        if($order->status != 8 && $order->status != -1) return $this->error ('订单状态不正确');
        $order->is_delete = 1;
        $order->edit_time = date('Y-m-d H:i:s');;
        $order->save();
        return $this->success('删除成功');
    }
    
    public function cancelOrder()
    {
        $order_id=$this->request->param('order_id/d',0);
        if(empty($order_id)) return $this->error('订单不存在');
        $params=[
            'member_id'=>$this->request->memberId,
            'order_id'=>$order_id,
        ];

        $order=GoodsOrderModel::find($order_id);
        if(null === $order) $this->error('订单不存在');
        Db::startTrans();
        try{
            $order_logic = OrderLogic::init($this->request->shopId);
            $order_logic[$order->order_type]->cancelOrder($params);
            Db::commit();
            return $this->success('成功');
        } catch (\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    /**
     * 获取店铺配送设置信息
     */
    public function getShopSendInfo(){
        $send_type = $this->request->param('send_type/d',0);//配送方式：1快递2同城3自提
        $is_default = $this->request->param('is_default/d',0);//是否查询默认配送方式

        if($is_default>0){
            $shop = ShopModel::find($this->request->shopId);
            $send_type = $shop->default_send_type;

            //            //获取默认配送方式
//            $send = new Send($this->app);
//            $send_type = $send->defaultSendType();
//
//            if($send_type<1){
//                return $this->success(['send_info'=>null]);
//
//            }
            if($send_type<1){
                //默认为自提
                if(null === $self_setting=SendSelfModel::where([['shop_id','=',$this->request->shopId]])->json(['order_time_slot','order_self_time'],true)->find()){

                    $self_setting = new SendSelfModel();
                    $self_setting->shop_id = $this->request->shopId;
                    $self_setting->save();

                    ShopModel::where([['shop_id','=',$this->request->shopId]])->update(['default_send_type'=>2]);
                }

            }


        }

        //获取配送设置信息
        $detail = $this->getSendInfo($send_type,$is_default);

        return $this->success([
            'default_send_type'=>$send_type,
            'detail' => $detail
        ]);
    }

    /**
     * 获取配送设置信息
     */
    protected function getSendInfo($send_type = 0,$is_default = 0){
        if($is_default)  $where[]=['is_open','=',1];

        $where[]=['shop_id','=',$this->request->shopId];

        $send_info_arr = '';

        if($send_type == 1){
//            if(null !==  $send_info = SendKuaidiModel::where($where)->find()){
//                $send_info_arr = $send_info->toArray();
//                unset($send_info_arr['send_kuaidi_id']);
//
//            }
            if(null !==  $send_info = FreightTemplateModel::where($where)->find()){
                $send_info_arr = $send_info->toArray();
                //unset($send_info_arr['send_kuaidi_id']);

            }

        }else if($send_type == 2){
            if(null !==  $send_info = SendSelfModel::where($where)->json(['order_self_time','order_time_slot'],true)->find()){
                $send_info_arr = $send_info->toArray();
                unset($send_info_arr['send_self_id']);

            }

        }else if($send_type == 3){
            if(null !==  $send_info = SendCityModel::where($where)->json(['send_scope','order_send_time','ladder_freight_distance','ladder_freight_price','forward_order_send','reduce_freight_price','order_time_slot'],true)->find()){
                $send_info_arr = $send_info->toArray();
                unset($send_info_arr['send_city_id']);

            }
        }
        return $send_info_arr;
    }
    
    
}
